package cn.vonce.common.bean;


import cn.vonce.common.enumerate.ResultCode;
import cn.vonce.common.utils.FastJsonUtil;
import cn.vonce.common.utils.StringUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 用于返回数据的结果集(Result Set)
 *
 * @author jovi
 * @version 1.0
 * @email 766255988@qq.com
 * @date 2017年5月24日上午11:32:38
 */
public class RS<T> extends HashMap<String, Object> {

    private static final Logger logger = LoggerFactory.getLogger(RS.class);

    public static final String CODE = "code";
    public static final String MSG = "msg";
    public static final String DATA = "data";

    public RS() {
        super();
    }

    public RS(Map<String, Object> map) {
        super(map);
    }

    public Integer getCode() {
        Object value = super.get(RS.CODE);
        if (value == null) {
            return null;
        }
        return Integer.parseInt(value.toString());
    }

    public void setCode(Integer code) {
        this.put(RS.CODE, code);
    }

    public String getMsg() {
        Object value = super.get(RS.CODE);
        if (value == null) {
            return null;
        }
        return value.toString();
    }

    public void setMsg(String msg) {
        this.put(RS.MSG, msg);
    }

    public T getData() {
        return (T) super.get(RS.DATA);
    }

    public void setData(T data) {
        this.put(RS.DATA, data);
    }

    public Object remove(String key) {
        return super.remove(key);
    }

    /**
     * 服务器内部错误
     *
     * @return
     */
    public static RS error() {
        return newRS(ResultCode.ERROR.getCode(), "系统错误", null);
    }

    /**
     * 服务器内部错误
     *
     * @param msg
     * @return
     */
    public static RS error(String msg) {
        return newRS(ResultCode.ERROR.getCode(), msg, null);
    }

    /**
     * 服务器内部错误(可返回JSONP)
     *
     * @param msg
     * @param request
     * @param response
     */
    public static void errorJSONP(String msg, HttpServletRequest request, HttpServletResponse response) {
        RS.writer(RS.toJsonOrJsonp(newRS(ResultCode.ERROR.getCode(), msg, null), request), request, response);
    }

    /**
     * 坏请求
     *
     * @return
     */
    public static RS bad() {
        return newRS(ResultCode.BAD.getCode(), "坏请求(请检查参数)", null);
    }

    /**
     * 坏的请求
     *
     * @param msg
     * @return
     */
    public static RS bad(String msg) {
        return newRS(ResultCode.BAD.getCode(), msg, null);
    }

    /**
     * 坏的请求(可返回JSONP)
     *
     * @param msg
     * @param request
     * @param response
     */
    public static void badJSONP(String msg, HttpServletRequest request, HttpServletResponse response) {
        RS.writer(RS.toJsonOrJsonp(newRS(ResultCode.BAD.getCode(), msg, null), request), request, response);
    }

    /**
     * 非法请求
     *
     * @param msg
     * @return
     */
    public static RS unAuthorized(String msg) {
        return newRS(ResultCode.UNAUTHORIZED.getCode(), msg, null);
    }

    /**
     * 非法请求(可返回JSONP)
     *
     * @param msg
     * @param request
     * @param response
     */
    public static void unAuthorizedJSONP(String msg, HttpServletRequest request, HttpServletResponse response) {
        RS.writer(RS.toJsonOrJsonp(newRS(ResultCode.UNAUTHORIZED.getCode(), msg, null), request), request, response);
    }

    /**
     * 返回成功状态
     *
     * @return
     */
    public static RS success() {
        return newRS(ResultCode.SUCCESS.getCode(), "操作成功", null);
    }

    /**
     * 返回成功状态
     *
     * @param msg
     * @return
     */
    public static RS success(String msg) {
        return newRS(ResultCode.SUCCESS.getCode(), msg, null);
    }

    /**
     * 返回成功状态
     *
     * @param data
     * @return
     */
    public static <T> RS success(T data) {
        return newRS(ResultCode.SUCCESS.getCode(), "操作成功", data);
    }

    /**
     * 返回成功状态及数据
     *
     * @param msg
     * @param data
     * @return
     */
    public static <T> RS success(String msg, T data) {
        return newRS(ResultCode.SUCCESS.getCode(), msg, data);
    }

    /**
     * 返回成功状态及数据(可返回JSONP)
     *
     * @param msg
     * @param data
     * @param request
     * @param response
     */
    public static <T> void successJSONP(String msg, T data, HttpServletRequest request, HttpServletResponse response) {
        RS.writer(RS.toJsonOrJsonp(newRS(ResultCode.SUCCESS.getCode(), msg, data), request), request, response);
    }

    /**
     * 返回自定义状态及数据
     *
     * @param hashMap
     * @return
     */
    public static RS custom(HashMap<String, Object> hashMap) {
        return new RS(hashMap);
    }

    /**
     * 返回自定义状态及数据(可返回JSONP)
     *
     * @param hashMap
     * @param request
     * @param response
     */
    public static void customJSONP(HashMap<String, Object> hashMap, HttpServletRequest request, HttpServletResponse response) {
        RS.writer(RS.toJsonOrJsonp(hashMap, request), request, response);
    }

    /**
     * 返回逻辑错误或非异常的错误状态
     *
     * @return
     */
    public static RS others() {
        return newRS(ResultCode.OTHERS.getCode(), "操作失败", null);
    }

    /**
     * 返回逻辑错误或非异常的错误状态
     *
     * @param msg
     * @return
     */
    public static RS others(String msg) {
        return newRS(ResultCode.OTHERS.getCode(), msg, null);
    }

    /**
     * 返回逻辑错误或非异常的错误状态(可返回JSONP)
     *
     * @param msg
     * @param request
     * @param response
     */
    public static void othersJSONP(String msg, HttpServletRequest request, HttpServletResponse response) {
        RS.writer(RS.toJsonOrJsonp(newRS(ResultCode.OTHERS.getCode(), msg, null), request), request, response);
    }

    /**
     * new RS
     *
     * @param code
     * @param msg
     * @param data
     * @return
     */
    public static <T> RS newRS(int code, String msg, T data) {
        RS<T> rs = new RS();
        rs.setCode(code);
        rs.setMsg(msg);
        if (data != null) {
            rs.setData(data);
        }
        return rs;
    }

    /**
     * 如果请求参数中有callback参数，返回jsonp格式
     *
     * @param object
     * @param request
     * @return
     */
    public static String toJsonOrJsonp(Object object, HttpServletRequest request) {
        StringBuffer sb = new StringBuffer();
        String callback = request.getParameter("callback");
        if (StringUtil.isNotBlank(callback)) {
            sb.append(callback + "(");
            sb.append(FastJsonUtil.obj2Json(object));
            sb.append(");");
        } else {
            sb.append(FastJsonUtil.obj2Json(object));
        }
        return sb.toString();
    }

    /**
     * 如果有callback参数且不为空设置文档类型为 application/javascript;否则为application/json;
     *
     * @param data
     * @param request
     * @param response
     */
    public static void writer(String data, HttpServletRequest request, HttpServletResponse response) {
        PrintWriter printWriter = null;
        try {
            response.setCharacterEncoding("UTF-8");
            if (StringUtil.isNotEmpty(request.getParameter("callback"))) {
                response.setContentType("application/javascript; charset=utf-8");
            } else {
                response.setContentType("application/json; charset=utf-8");
            }
            printWriter = response.getWriter();
            printWriter.write(data);
            // 请求日志
            logger.info(request.getServletPath() + " 的响应内容：" + data);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            printWriter.close();
        }
    }
}
